package com.example.exam.servlet;

import com.example.exam.dao.StudentDAO;
import com.example.exam.entity.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 登录Servlet
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private StudentDAO studentDAO = new StudentDAO();
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // 转发到登录页面
        request.getRequestDispatcher("/WEB-INF/views/login.jsp").forward(request, response);
    }
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // 设置字符编码
        request.setCharacterEncoding("UTF-8");
        
        // 获取表单参数
        String studentId = request.getParameter("studentId").trim();
        String password = request.getParameter("password").trim();
        
        // 添加调试信息
        System.out.println("登录尝试 - 学号: " + studentId + ", 密码: " + password);
        
        // 验证登录
        if (studentDAO.validateLogin(studentId, password)) {
            // 登录成功，获取学生信息
            Student student = studentDAO.getStudentById(studentId);
            
            if (student != null) {
                System.out.println("登录成功 - 学生: " + student.getName());
                
                // 将学生信息存入session
                HttpSession session = request.getSession();
                session.setAttribute("student", student);
                
                // 重定向到首页
                response.sendRedirect(request.getContextPath() + "/dashboard");
            } else {
                System.out.println("登录验证成功但获取学生信息失败");
                request.setAttribute("error", "获取学生信息失败");
                request.getRequestDispatcher("/WEB-INF/views/login.jsp").forward(request, response);
            }
        } else {
            // 登录失败，返回错误信息
            System.out.println("登录失败 - 学号: " + studentId);
            request.setAttribute("error", "学号或密码错误");
            request.getRequestDispatcher("/WEB-INF/views/login.jsp").forward(request, response);
        }
    }
}